<?php

/**
 * 视图渲染
 */
namespace App;


use EasySwoole\Template\RenderInterface;

class Template implements RenderInterface
{
    protected $template;
    function __construct()
    {
        $config = [
            'view_path' => EASYSWOOLE_ROOT . '/App/View/',
            'cache_path' => EASYSWOOLE_ROOT . 'Temp/runtime/',
        ];
        $this->template = new \think\Template($config);
    }

    public function render(string $template, array $data = [], array $options = []): ?string
    {
        // TODO: Implement render() method.
        ob_start();
        $this->template->assign($data);
        $this->template->fetch($template);
        $content = ob_get_contents() ;

        //替换template中的文件夹路径
        $content = $this->parseTemplate($content);

        return $content;
    }

    public function afterRender(?string $result, string $template, array $data = [], array $options = [])
    {
        // TODO: Implement afterRender() method.
    }

    public function onException(\Throwable $throwable): string
    {
        // TODO: Implement onException() method.
        $msg = "{$throwable->getMessage()} at file:{$throwable->getFile()} line:{$throwable->getLine()}";
        trigger_error($msg);
        return $msg;
    }

    /**
     * 将模板中定义的常量替换
     * @param string $content
     * @return string
     */
    protected function parseTemplate(string $content) :string {
        $content = str_replace(['__PUBLIC__', '__STATIC__'], [__PUBLIC__, __STATIC__], $content);
        return $content;
    }

}